﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Verse;
using Verse.AI.Group;
using Verse.Noise;

namespace SZ.Mech
{
    public class IncidentWorker_SZ : IncidentWorker
    {
        protected override bool CanFireNowSub(IncidentParms parms)
        {
            return SZ_DefOf.SZ_HeavenForgedCelestiall != null;
        }

        protected override bool TryExecuteWorker(IncidentParms parms)
        {

            Map map = (Map)parms.target;
            float points = Mathf.Max(parms.points, 600f);
            if (points > 50000)
            {
                points = 50000;
            }
            int createRandomSize = (int)(points / 5000f);


            Faction FactionHeavenForged = Find.FactionManager.FirstFactionOfDef(SZ_DefOf.SZ_HeavenForgedCelestiall);
            Lord lord = LordMaker.MakeNewLord(FactionHeavenForged, new LordJob_AssaultColony(), map);

            ///核心建筑物
            ThingDef shipPartDef = def.mechClusterBuilding;
            IntVec3 intVec;
            Building coreThing = null;
            if (shipPartDef != null)
            {
                intVec = FindDropPodLocation(map, (IntVec3 spot) => CanPlaceAt(spot));
                bool CanPlaceAt(IntVec3 loc)
                {
                    //占用的区域
                    CellRect cellRect = GenAdj.OccupiedRect(loc, Rot4.North, shipPartDef.Size);
                    if (loc.Fogged(map) || !cellRect.InBounds(map))
                    {
                        return false;
                    }

                    if (!DropCellFinder.SkyfallerCanLandAt(loc, map, shipPartDef.Size))
                    {
                        return false;
                    }
                    foreach (IntVec3 item2 in cellRect)
                    {
                        RoofDef roof = item2.GetRoof(map);
                        if (roof != null && roof.isNatural)
                        {
                            return false;
                        }
                    }

                    return GenConstruct.CanBuildOnTerrain(shipPartDef, loc, map, Rot4.North);
                }
                if (intVec == IntVec3.Invalid)
                {
                    return false;
                }
                coreThing = (Building)ThingMaker.MakeThing(shipPartDef);
                SubMechCluster subMechCluster = coreThing.GetComp<SubMechCluster>();
                if (subMechCluster != null)
                {
                    subMechCluster.IncidentParms = parms;
                }
                coreThing.SetFaction(FactionHeavenForged);
                lord.AddBuilding(coreThing);
            }
            else
            {
                //查找围攻位置
                intVec = RCellFinder.FindSiegePositionFrom(DropCellFinder.FindRaidDropCenterDistant(map, allowRoofed: true), map, allowRoofed: true);
            }

            ///建筑物
            List<ThingDef> statueThingDefs = new List<ThingDef>();
            statueThingDefs.Add(SZ_DefOf.SZ_StatueSoldierA);
            statueThingDefs.Add(SZ_DefOf.SZ_StatueSoldierB);
            statueThingDefs.Add(SZ_DefOf.SZ_StatueOfficerA);
            statueThingDefs.Add(SZ_DefOf.SZ_StatueOfficerB);
            float usePoint = points;
  
            ///底座
            List<Building> statueThings = new List<Building>();
            while (usePoint > 0)
            {
               var useDef = statueThingDefs[UnityEngine.Random.Range(0, statueThingDefs.Count)];
                Building statuebuild = (Building)ThingMaker.MakeThing(useDef);
                statuebuild.SetFaction(FactionHeavenForged);
                statueThings.Add(statuebuild);
                CompPawnSpawnOnWakeup compPawnSpawnOnWakeup =  statuebuild.TryGetComp<CompPawnSpawnOnWakeup>();
                usePoint -= compPawnSpawnOnWakeup.points;
                CompCanBeDormant compCanBeDormant = statuebuild.TryGetComp<CompCanBeDormant>();
                compCanBeDormant.ToSleep();
                lord.AddBuilding(statuebuild);
            }
           
            ///炮塔
            MechClusterProps props = this.def.GetModExtension<MechClusterProps>();
            List<Thing> listTurret = new List<Thing>();
            if (props != null)
            {
                foreach (Thing item in GenerateBuildings(props.additionalBuildings, points))
                {
                    item.SetFaction(FactionHeavenForged);
                    listTurret.Add(item);
                }
            }

            if(this.def.defName== "BoosIncidentWorker_SZ")
            {
                Building statuebuild = (Building)ThingMaker.MakeThing(SZ_DefOf.SZ_Flashstorm);
                statuebuild.SetFaction(FactionHeavenForged);
                //statueThings.Add(statuebuild);
                CompPawnSpawnOnWakeup compPawnSpawnOnWakeup = statuebuild.TryGetComp<CompPawnSpawnOnWakeup>();
                CompCanBeDormant compCanBeDormant = statuebuild.TryGetComp<CompCanBeDormant>();
                compCanBeDormant.ToSleep();

                //lord.AddBuilding(statuebuild);
                GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.MeteoriteIncoming, statuebuild), intVec + new IntVec3(10, 0, 0), map);//高空坠落物
                //GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.CrashedShipPartIncoming, statuebuild), intVec + new IntVec3(10, 0, 0), map);//高空坠落物
                //GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.CrashedShipPartIncoming, statuebuild), intVec+new IntVec3(10,0,0), map);//高空坠落物
                //GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(SZ_DefOf.SZ_Flashstorm, coreThing), intVec, map);//高空坠落物
            }


            ///掉落
            MiaoUtility.DropThingsNearPro(intVec, createRandomSize, map, statueThings);
            //DropPodUtility.DropThingsNear(intVec, map, statueThings);
            DropPodUtility.DropThingsNear(intVec, map, listTurret);

            if (coreThing != null)
            {
                GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.MeteoriteIncoming, coreThing), intVec, map);//高空坠落物
                SendStandardLetter(parms, coreThing);
            }
            else
            {
                SendStandardLetter(parms, statueThings[0]);
            }
            return true;
        }
        private static IEnumerable<Thing> GenerateBuildings(List<ThingDef> buildings, float point)
        {
            int count = (int)point / 500 + 1;
            int length = buildings.Count;
            for (int i = 0; i < count; i++)
            {
                ThingDef def = buildings[Rand.Range(0, length - 1)];
                Thing thing = ThingMaker.MakeThing(def);
                yield return thing;
            }
            yield break;
        }
        private static IntVec3 FindDropPodLocation(Map map, Predicate<IntVec3> validator)
        {
            for (int i = 0; i < 200; i++)
            {
                IntVec3 intVec = RCellFinder.FindSiegePositionFrom(DropCellFinder.FindRaidDropCenterDistant(map, allowRoofed: true), map, allowRoofed: true);
                if (validator(intVec))
                {
                    return intVec;
                }
            }
            return IntVec3.Invalid;
        }
    }
}
